from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QLabel, 
                                 QComboBox, QPushButton, QMessageBox, QStackedWidget, QGroupBox, QLineEdit, QHBoxLayout, QTreeWidget, QGridLayout, QDateTimeEdit, QRadioButton, QButtonGroup)
from PyQt5.QtCore import QDate, QTimer
from core.device_manager import DeviceManager
from core.constants import DeviceType, CommunicationType
import subprocess
# 添加串口相关的库
import serial.tools.list_ports
from nav.rfid_helper import RFIDHelper

class DevicePage(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.device_manager = DeviceManager()
        # 保存主窗口引用
        self.main_window = parent
        # 创建 RFIDHelper 实例
        self.rfid_helper = RFIDHelper()
        self.setup_ui()
        # 初始化完成后自动刷新设备列表
        QTimer.singleShot(100, self.refresh_devices)

    def setup_ui(self):
        layout = QVBoxLayout(self)
        
        # 标题
        title = QLabel("设备选择")
        title.setStyleSheet("font-size: 24px; margin: 20px;")
        layout.addWidget(title)

        # 设备类型选择
        self.device_type_group = QGroupBox("设备类型")
        self.device_type_layout = QVBoxLayout()
        self.device_types = {
            "2.4GHz有源读卡器 [AA系列]": DeviceType.AA_SERIES,
            "915MHz无源读卡器 [AP系列]": DeviceType.AP_SERIES,
            # ... 其他设备类型
        }
        
        # 通信方式选择
        self.comm_type_group = QGroupBox("通信方式")
        self.comm_type_layout = QVBoxLayout()
        self.comm_types = {
            "RS232": CommunicationType.RS232,
            "RS485": CommunicationType.RS485,
            "TCP/IP": CommunicationType.TCPIP,
            "WIFI": CommunicationType.WIFI,
            "USB": CommunicationType.USB
        }
        
        # 参数设置区域
        self.param_stack = QStackedWidget()
        self.setup_serial_widget()
        self.setup_network_widget()
        self.setup_usb_widget()

        # 设备选择下拉框
        self.device_combo = QComboBox()
        layout.addWidget(QLabel("请选择RFID设备："))
        layout.addWidget(self.device_combo)
        
        # 刷新设备按钮
        refresh_btn = QPushButton("刷新设备列表")
        refresh_btn.clicked.connect(self.refresh_devices)
        layout.addWidget(refresh_btn)

        # 确认按钮
        confirm_btn = QPushButton("确认连接")
        confirm_btn.clicked.connect(self.confirm_device)
        layout.addWidget(confirm_btn)

        # 添加弹性空间
        layout.addStretch()

    def confirm_device(self):
        """确认设备连接"""
        if self.device_combo.currentIndex() == -1:
            QMessageBox.warning(self, "警告", "请选择一个设备")
            return

        device_id = self.device_combo.currentData()
        
        # 使用 RFIDHelper 获取设备列表并尝试连接
        devices = self.rfid_helper.get_usb_devices()
        selected_device = next((dev for dev in devices if dev['key'] == device_id), None)
        
        if selected_device:
            print("\n=== 开始连接USB设备 ===")
            # 尝试连接设备
            retry_count = 3
            for i in range(retry_count):
                try:
                    if i > 0:
                        print(f"第 {i+1} 次尝试连接...")
                    if self.rfid_helper.connect_usb(selected_device):
                        print("设备连接成功")
                        self.main_window.switch_to_main_page()
                        return
                except Exception as e:
                    print(f"连接失败: {e}")
                    if i == retry_count - 1:
                        QMessageBox.critical(self, "错误", f"USB设备连接失败: {str(e)}")
                        return
                QTimer.singleShot(1000, lambda: None)  # 等待1秒后重试
        else:
            QMessageBox.critical(self, "错误", "未找到选中的设备")

    def refresh_devices(self):
        """刷新设备列表"""
        self.device_combo.clear()
        
        # 使用 RFIDHelper 获取 USB 设备列表
        devices = self.rfid_helper.get_usb_devices()
        if not devices:
            self.device_combo.addItem("未检测到RFID设备")
            return
            
        for device in devices:
            # 构建设备显示名称
            device_name = f"{device['product_string']} ({device['manufacturer_string']})"
            # 使用设备的 key 作为唯一标识符
            self.device_combo.addItem(device_name, device['key'])

    def setup_serial_widget(self):
        """设置串口参数界面"""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        
        # COM口选择
        self.port_combo = QComboBox()
        self.refresh_ports()  # 刷新可用串口
        layout.addWidget(QLabel("串口:"))
        layout.addWidget(self.port_combo)
        
        # 波特率选择
        self.baud_combo = QComboBox()
        self.baud_combo.addItems(['9600', '19200', '38400', '57600', '115200'])
        layout.addWidget(QLabel("波特率:"))
        layout.addWidget(self.baud_combo)
        
        self.param_stack.addWidget(widget)

    def setup_network_widget(self):
        """设置网络参数界面"""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        
        # IP地址输入
        self.ip_input = QLineEdit()
        self.ip_input.setPlaceholderText("192.168.1.100")
        layout.addWidget(QLabel("IP地址:"))
        layout.addWidget(self.ip_input)
        
        # 端口输入
        self.port_input = QLineEdit()
        self.port_input.setPlaceholderText("8080")
        layout.addWidget(QLabel("端口:"))
        layout.addWidget(self.port_input)
        
        self.param_stack.addWidget(widget)

    def refresh_ports(self):
        """刷新可用串口列表"""
        self.port_combo.clear()
        try:
            # 获取系统中所有可用的串口
            ports = list(serial.tools.list_ports.comports())
            for port in ports:
                # 添加串口名称和描述
                self.port_combo.addItem(f"{port.device} - {port.description}", port.device)
            
            if not ports:
                self.port_combo.addItem("未检测到串口设备")
        except Exception as e:
            print(f"获取串口列表错误: {str(e)}")
            self.port_combo.addItem("获取串口列表失败")

    def setup_usb_widget(self):
        """设置USB参数界面"""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        
        # USB设备信息显示
        self.usb_info = QLabel("USB设备将自动检测")
        layout.addWidget(self.usb_info)
        
        self.param_stack.addWidget(widget)

class CustomStackedWidget(QStackedWidget):
    def switch_to_page(self, index):
        self.setCurrentIndex(index) 